package com.dhcc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhcc.entity.User;
import com.dhcc.repository.UserRepository;
import com.dhcc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "findUser")
    public User findById(@RequestParam("uid") Integer uid) {
        User u = userService.getUserById(uid);
        return u;
    }

    @RequestMapping(value = "findAll")
    public List<User> findAll() {
        List<User> users = userService.listUser();
        return users;
    }

    @RequestMapping(value = "delUser")
    public void delById(@RequestParam("uid") Integer uid) {
        userService.delUser(uid);
    }

    @RequestMapping(value = "addUser")
    public void addUser(User user) {
        userService.addUser(user);
    }

    @RequestMapping(value = "findByUsername")
    public JSONObject findByUsername(@RequestParam("name") String username) {
//        List<User> userByUsername = userRepository.findUserByUsername(username);
        List<User> userByUsername = userRepository.etUser(username);
        JSONObject js = new JSONObject();
        JSONArray arr = new JSONArray();
        for (User user : userByUsername) {
            JSONObject json = new JSONObject();
            json.put("username", user.getUsername());
            json.put("password", user.getPassword());
            arr.add(json);
        }
        js.put("users", arr);
        js.put("code", true);
        return js;
    }
}
